package com.zxy.ziems.server.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxy.btp.common.response.PageResult;
import com.zxy.btp.web.util.TokenUtils;
import com.zxy.ziems.server.constant.PointDataType;
import com.zxy.ziems.server.convert.PointDataConvert;
import com.zxy.ziems.server.classify.pojo.entity.Classify;
import com.zxy.ziems.server.domain.ClassifyPointRel;
import com.zxy.ziems.server.domain.PointData;
import com.zxy.ziems.server.dto.PointDataDto;
import com.zxy.ziems.server.dto.PointDataExportDto;
import com.zxy.ziems.server.dto.PointDataQueryDto;
import com.zxy.ziems.server.listener.PointDataListener;
import com.zxy.ziems.server.classify.mapper.ClassifyMapper;
import com.zxy.ziems.server.mapper.ClassifyPointRelMapper;
import com.zxy.ziems.server.mapper.PointDataMapper;
import com.zxy.ziems.server.service.PointDataService;
import com.zxy.ziems.server.vo.PointDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName PointDataServiceImpl
 * @Description
 * @Author 邓伟
 * @Date 2023/12/4 13:57
 * @Version 1.0
 */
@Service
public class PointDataServiceImpl extends ServiceImpl<PointDataMapper, PointData> implements PointDataService {

    @Autowired
    private PointDataMapper pointDataMapper;
    @Autowired
    private ClassifyMapper classifyMapper;
    @Autowired
    private ClassifyPointRelMapper classifyPointRelMapper;

    @Override
    @Transactional(readOnly = true)
    public PageResult<PointDataVo> pageList(PointDataQueryDto pointDataQueryDto) {
        //计算时间间隔
        Page<PointData> page = pointDataMapper.selectPageList(new Page<>(pointDataQueryDto.getPageNo(), pointDataQueryDto.getPageSize()), pointDataQueryDto);
        List<PointData> records = page.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return new PageResult<>(0L,null);
        }
        List<PointDataVo> list = new ArrayList<>();
        //根据数据类型处理时间格式
        for (PointData record : records) {
            PointDataVo pointDataVo = PointDataConvert.INSTANCE.pointDataToPointDataVo(record);
            LocalDateTime dataTime = record.getDataTime();
            String dataTimeStr = null;
            if (PointDataType.AUTO == record.getDataObtainType()) {
                dataTimeStr = dataTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            }else if (PointDataType.HAND_DAY == record.getDataObtainType()) {
                dataTimeStr = dataTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            }else {
                String format = dataTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                dataTimeStr = format.substring(0,7);
            }
            pointDataVo.setDataTime(dataTimeStr);
            list.add(pointDataVo);
        }
        return new PageResult<>(page.getTotal(),list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateData(PointDataDto pointDataDto) {
        PointData pointData = new PointData();
        pointData.setId(pointDataDto.getId());
        pointData.setDataValue(pointDataDto.getDataValue());
        pointData.setUpdateUserId(TokenUtils.getUserIdByToken());
        pointData.setUpdateTime(LocalDateTime.now());
        pointData.setUpdateUserName(TokenUtils.getUserNameByToken());
        pointDataMapper.updateById(pointData);
    }

    @Override
    public void export(MultipartFile file, String classifyId) throws IOException {
        String userId = TokenUtils.getUserIdByToken();
        String userName = TokenUtils.getUserNameByToken();
        Classify classify = classifyMapper.selectById(classifyId);
        //查询此分类下的点位编码列表
        QueryWrapper<ClassifyPointRel> query = new QueryWrapper<>();
        query.lambda().eq(ClassifyPointRel::getClassifyId,classifyId).select(ClassifyPointRel::getPointCode);
        List<ClassifyPointRel> list = classifyPointRelMapper.selectList(query);
        Set<String> pointCodeSet = list.stream().map(ClassifyPointRel::getPointCode).collect(Collectors.toSet());
        EasyExcel.read(file.getInputStream(), PointDataExportDto.class
                , new PointDataListener(pointDataMapper,userId,userName,classify,pointCodeSet)).sheet().doRead();
    }
}
